/*
 * Copyright 2008 Wink Saville
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.saville.mc;

import java.lang.Thread;
import com.saville.debug.Log;
import com.saville.msgcomp.*;


/*
 * A MsgComp with its own thread
 */
abstract public class ActiveMc extends Mc implements IActiveMc, Runnable {

    /*
     * Constructor
     */
    public ActiveMc(String name, boolean doSendCmdStarted) {
        Log.d(df, "ActiveMc: %s Mc() E", name);

        // Init mName so our Log's print something useful
        mName = name;

        // Create the new thread
        Thread thr = new Thread(null, this, name);
        thr.start();

        // Wait for the new thread to be started
        while (mRunning != 1) {
            sleep(100);
        }

        // Now Mc.init
        init(name, mMsgPump, doSendCmdStarted);

        Log.d(df, "ActiveMc: %s Mc() X", mName);
    }
    
    /*
     * Constructor
     */
    public ActiveMc(String name) {
        this(name, true);
    }
    
    /*
     * Stop the ActiveMc
     */
    public void stopProcessing() {
        mMsgPump.stopProcessing();
    }
    
    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Runnable#run()
     */
    public void run() {
        Log.d(df, "ActiveMc: %s run() E", mName);
        MsgPump.prepare();
        mMsgPump = MsgPump.myMsgPump();
        mRunning = 1;
        MsgPump.loop();
        Log.d(df, "ActiveMc: %s run() X", mName);
    }

    private void sleep(int millisecs) {
        synchronized (this) {
            try {
                wait(100);
            } catch (InterruptedException e) {
            }
        }
    }

    protected volatile int mRunning;
    protected MsgPump mMsgPump;
}
